package com.itheima.security.springboot.controller;

import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpSession;

/**
 * @author xiaoxiaokui
 * @description: 登录接口
 * @date 2019/11/18
 **/
@RestController
public class LoginController {

    /**
     * @description loginSuccess
     * @author xiaoxiaokui
     * @date 2019/11/18
     * @param
     * @return java.lang.String
     * @modifier
     * @note
     **/
    @RequestMapping(
            value = "/login-success",
            produces = {"text/plain;charset=UTF-8"})
    public String loginSuccess() {
        return this.getUsername() + "登录成功";
    }

    @PreAuthorize("hasAuthority('p1')")  // 表示有用p1权限才可以访问
    @GetMapping(value = "/r/r1", produces = "text/plain;charset=utf-8")
    public String r1(HttpSession session) {
        return this.getUsername() + "访问资源r1";
    }

//    @PreAuthorize("hasAuthority('p2')")
    @GetMapping(value = "/r/r2", produces = "text/plain;charset=utf-8")
    public String r2(HttpSession session) {
        return this.getUsername() + "访问资源r2";
    }

    /***
     * @Description: 获取用户名称
     * @Param: []
     * @return: java.lang.String
     * @Author: xiaoxiaokui
     * @Date: 2019/11/21
     */
    private String getUsername() {
        String username = null;
        // 当前认证通过的用户身份
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        // 用户身份
        Object principal = authentication.getPrincipal();
        if (principal == null) {
            username = "匿名";
            return username;
        }
        if (principal instanceof org.springframework.security.core.userdetails.UserDetails) {
            UserDetails userDetails = (UserDetails) principal;
            username = userDetails.getUsername();
        } else {
            username = principal.toString();
        }
        return username;
    }
}
